package cn.com.dhcc.app.pub.core.util;

import cn.com.dhcc.app.core.exception.CompressException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.compresshandler.CompressResult;
import cn.com.dhcc.app.core.handler.compresshandler.CompressService;
import cn.com.dhcc.app.core.handler.compresshandler.CompressServiceFactory;
import cn.com.dhcc.app.core.handler.compresshandler.CompressStatic;
import cn.com.dhcc.app.core.service.Log;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import java.io.File;

/**
 * @日期：2017/3/13 12:05
 * @作者：张洪涛
 * @版权所有：东华软件
 * @版本：1.0
 */
public class FileUtil {
    private static Logger logger = Log.getLogger(Log.LOGTYPE.DDI);
    /**
     * 解压文件
     * @param needCompressFile 需要解压的文件
     * @param outPath 解压后的文件路径
     * @return true 解压成功  false 解压失败
     */
    public static String unCompress (File needCompressFile, String outPath){
        //获取解压缩处理的service
        CompressService compressService = CompressServiceFactory.createCompressService(CompressStatic.COMPRESS_ALGORITHM.JAVA_GZIP);
        String after = null;
        try {
            String fileName = needCompressFile.getName();
            if (StringUtils.isEmpty(fileName)){
                return after;
            }
            after = outPath + File.separator+fileName.substring(0,fileName.indexOf(".edata"));//解压缩后文件名
            after = compressService.uncompress(needCompressFile, after, true);
        } catch (CompressException e) {
            logger.error("[unCompress]解压文件发生异常", e);
        }
        return after;
    }

    /**
     * 压缩文件
     * @param uploadRoot
     * @param before
     * @return
     * @throws ServiceException
     */
    public static CompressResult<String> compressFile(String uploadRoot, File before) throws ServiceException{
        try {
            CompressService compressService = CompressServiceFactory.createCompressService(CompressStatic.COMPRESS_ALGORITHM.JAVA_GZIP);
            String after = uploadRoot+File.separator+before.getName()+".edata";//压缩后文件名
            CompressResult<String> sresult = compressService.compress(before,after,true);
            logger.info("压缩文件成功:" + sresult.getCommpressResultObj());
            return sresult;
        } catch (Exception e1) {
            logger.error("压缩文件" + before + "发生异常",e1);
            throw new ServiceException("压缩文件" + before + "发生异常",e1);
        }
    }
}
